package net.huafv.authoritycontrol.security;


import cn.hutool.core.util.StrUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.huafv.authoritycontrol.admin.entity.SysUser;
import net.huafv.authoritycontrol.admin.service.SysUserService;
import net.huafv.authoritycontrol.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;


@Component
public class JwtAuthorFilter extends OncePerRequestFilter {

	@Autowired
	JwtUtil jwtUtil;

	@Autowired
	SysUserService sysUserService;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
		String jwt = request.getHeader("Authorization");

		if (StrUtil.isBlankOrUndefined(jwt)) {
			chain.doFilter(request, response);
			return;
		}

		if( JwtUtil.checkToken("huafv", jwt, "fly")){
			String username = (String) Objects.requireNonNull(JwtUtil.getClaims("huafv", jwt)).get("username");
			System.out.println(username);
			SysUser sysUser = sysUserService.getByUsername(username);
			System.out.println(sysUser);
		}
		chain.doFilter(request, response);
	}
}

